//
//  LoginViewController.m
//  zhiche--delivery
//
//  Created by LeeBruce on 16/5/6.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "LoginViewController.h"
#import "Common.h"
#import <Masonry.h>
#import "ForgetpasswordViewController.h"
#import "RegisterViewController.h"
#import "WKProgressHUD.h"
#import "OrderTalkingViewController.h"
#import "RootViewController.h"
#import "SSKeychain.h"

#define leftMar 60

@interface LoginViewController ()<UITextFieldDelegate>

@property (nonatomic,strong) UITextField *phoneTextField;
@property (nonatomic,strong) UITextField *captchaTextField;

@property (nonatomic,strong) UIButton *captchaButton;
@property (nonatomic) int secondCountDown;

@property (nonatomic,strong) UIScrollView *scrollView;

@property (nonatomic,strong) WKProgressHUD *hud;
@property (nonatomic,copy) NSString *uuidString;



@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = WhiteColor;

    [self initSubviews];

}

-(void)initSubviews
{
    self.topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"慧运车"];
    
//    [self.topBackView.leftButton addTarget:self action:@selector(dismissSelf) forControlEvents:UIControlEventTouchUpInside];
    self.topBackView.leftButton.hidden = YES;
    self.topBackView.rightButton.hidden = YES;
    
    [self.view addSubview:self.topBackView];
    
    self.view.backgroundColor = WhiteColor;
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight)];
    self.scrollView.contentSize = CGSizeMake(screenWidth, screenHeight);
    [self.view addSubview:self.scrollView];
    self.scrollView.backgroundColor = WhiteColor;
    
    UIImageView *logoImageV = [[UIImageView alloc]initWithFrame:CGRectMake((screenWidth - 108)/2.0, 55 * kHeight, 108, 40)];
    logoImageV.image = [UIImage imageNamed:@"register_logo"];
    
    [self.scrollView addSubview:logoImageV];
    
    self.phoneTextField = [[UITextField alloc]init];
    self.phoneTextField.placeholder = @"请输入手机号";
    self.phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    self.captchaTextField = [[UITextField alloc]init];
    self.captchaTextField.placeholder = @"请输入6-14位密码";
    self.captchaTextField.secureTextEntry = YES;
    self.captchaTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    //手机号
    UIView *firstV = [self backViewWithFloat:(CGRectGetMaxY(logoImageV.frame) + 28 *kHeight ) andField:self.phoneTextField  andImage:[UIImage imageNamed:@"register_phone"]];
    
    [self.scrollView addSubview:firstV];
    
    //密码
    UIView *secondV = [self backViewWithFloat:CGRectGetMaxY(firstV.frame) andField:self.captchaTextField  andImage:[UIImage imageNamed:@"register_password"]];
    
    [self.scrollView addSubview:secondV];
    
    
    //注册
    UIButton *loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    loginButton.frame = CGRectMake( 18,CGRectGetMaxY(secondV.frame) + 30 *kHeight, screenWidth - 36, 35 * kHeight);
    loginButton.backgroundColor = YellowColor ;
    [loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [loginButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    [loginButton addTarget:self action:@selector(LoginButtonAction) forControlEvents:UIControlEventTouchUpInside];
    //    loginButton.layer.borderWidth = 0.5;
    //    loginButton.layer.borderColor = BlackColor.CGColor;
    loginButton.layer.cornerRadius = 5;
    loginButton.titleLabel.font = Font(15);
    
    
    [self.scrollView addSubview:loginButton];
    
    
    UIButton *forgetButton = [UIButton buttonWithType:UIButtonTypeCustom];
    forgetButton.frame = CGRectMake(0, CGRectGetMaxY(loginButton.frame) + 15, 110, 20);
    
    [forgetButton setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [forgetButton setTitleColor:YellowColor forState:UIControlStateNormal];
    forgetButton.titleLabel.font = Font(13);
    [self.scrollView addSubview:forgetButton];
    [forgetButton addTarget:self action:@selector(forgetButton) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton *registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    registerButton.frame = CGRectMake(screenWidth - 20 - 40,  CGRectGetMaxY(loginButton.frame) + 15, 40, 20);
    [registerButton setTitleColor:YellowColor forState:UIControlStateNormal];
    [registerButton setTitle:@"注册" forState:UIControlStateNormal];
    registerButton.titleLabel.font = Font(13);
//    [self.scrollView addSubview:registerButton];
    [registerButton addTarget:self action:@selector(registerButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    
}

#pragma mark 忘记密码
-(void)forgetButton{
    
    ForgetpasswordViewController *forgetVC = [[ForgetpasswordViewController alloc]init];
   
    [self.navigationController pushViewController:forgetVC animated:YES];
}

#pragma mark 注册
-(void)registerButtonAction
{
    
    RegisterViewController *registerVC = [[RegisterViewController alloc]init];
    
    [self.navigationController pushViewController:registerVC animated:YES];
}

-(UIButton *)backButtonWithString:(NSString *)title andFont:(NSInteger)integer andFrame:(CGRect)frame
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    
    //设置button下划线
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:title];
    NSRange strRange = {0,[str length]};
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:strRange];  //设置颜色
    [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
    
    [button setAttributedTitle:str forState:UIControlStateNormal];
    
    return button;
}


#pragma mark 验证码方法
-(void)captchaButtonAction:(UIButton *)sender
{
  
//    先判断手机号的正确
    NSString *regExp = @"^[1]([3][0-9]|[8][0-9]|[5][0-9]|45|47|76|77|78)[0-9]{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regExp];
    BOOL isRight = [pred evaluateWithObject:self.phoneTextField.text];
    
    if (isRight) {
 
        [sender setTintColor:GrayColor];
        sender.userInteractionEnabled = NO;
        _secondCountDown = 60;
        NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireAction:) userInfo:nil repeats:YES];
        [time fire];
        
        Common *c = [[Common alloc]init];
        
        NSString *string = [NSString stringWithFormat:@"%@login/%@",Main_interface,self.phoneTextField.text];
        
        NSDictionary *dic = @{@"phone":self.phoneTextField.text};
                
        [c afPostRequestWithUrlString:string parms:dic finishedBlock:^(id responseObj) {
            
            NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
            
            
        } failedBlock:^(NSString *errorMsg) {
            NSLog(@"%@",errorMsg);
        }];
        
        
        
    } else {
        
        [WKProgressHUD popMessage:@"手机号码不正确，请重新输入" inView:self.view duration:1.5 animated:YES];

//        [self showAlertControllerWithString:@"手机号码不正确，请重新输入" andInteger:0];
        
    }

}

-(void)timeFireAction:(NSTimer *)time
{
    _secondCountDown --;
    
    //设置button下划线
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"(%ds)",_secondCountDown]];
    NSRange strRange = {0,[str length]};
    [str addAttribute:NSForegroundColorAttributeName value:GrayColor range:strRange];  //设置颜色
    [self.captchaButton setAttributedTitle:str forState:UIControlStateNormal];

    
    if (_secondCountDown <= 0) {
        [time invalidate];
        self.captchaButton.userInteractionEnabled = YES;
        //设置button下划线
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"验证码"];
        NSRange strRange = {0,[str length]};
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:strRange];  //设置颜色
//        [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
        
        [self.captchaButton setAttributedTitle:str forState:UIControlStateNormal];

    }
}


#pragma mark 协议方法

-(void)protocolButton
{
    
}
#pragma mark 登录方法

-(void)LoginButtonAction
  {

      //获取uuid
      [self sendUUID];
      
      self.hud = [WKProgressHUD showInView:self.view withText:@"" animated:YES];
//      pushid
      NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

      NSString * pushid = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"pushid"]];
      

      NSDictionary *dic = @{@"phone":self.phoneTextField.text,
                            @"password":self.captchaTextField.text,
                            @"usertype":userType,
                            @"uuid":self.uuidString,
                            @"pushid":pushid};
      
      
      Common *c = [[Common alloc]init];
      [c afPostRequestWithUrlString:login_codeLogin parms:dic finishedBlock:^(id responseObj) {
          
        
          [self.hud dismiss:YES];

          
          NSDictionary *dictonary = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
          
          
          [WKProgressHUD popMessage:dictonary[@"message"] inView:self.view duration:1.5 animated:YES];
          
//          [self showAlertControllerWithString:dictonary[@"message"] andInteger:0];
          
          if ([[dictonary objectForKey:@"success"] boolValue]) {

              
              NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
              [userDefaults setObject:@"login" forKey:@"login"];

              [userDefaults setObject:dictonary[@"data"][@"Authorization"] forKey:login_token];
              
              
              [[NSNotificationCenter defaultCenter] postNotificationName:@"dismiss" object:self];

//              OrderTalkingViewController *orderTalk = [[OrderTalkingViewController alloc]init];
//              
//              [self presentViewController:orderTalk animated:YES completion:nil];
//              
              [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
//              //延迟执行
              dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                  
                  
                  [self dismissViewControllerAnimated:YES completion:^{
                      [[NSNotificationCenter defaultCenter] postNotificationName:@"dismiss" object:self];
                      
                  }];
                  [self.navigationController popViewControllerAnimated:YES];
                  
              });
          }
          
          
      } failedBlock:^(NSString *errorMsg) {
          
          [self.hud dismiss:YES];
//          [WKProgressHUD popMessage:errorMsg inView:self.view duration:1.5 animated:YES];

          NSLog(@"%@",errorMsg);
      }];
//
      
     

  }

#pragma mark 联系客服
-(void)callButton
{
    
}

-(void)showAlertControllerWithString:(NSString *)string andInteger:(NSInteger)integer
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:string message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:action1];
    [alertController addAction:action2];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
    if (integer == 1) {
        
        //延迟执行
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [alertController dismissViewControllerAnimated:YES completion:nil];
            
        });

    }
    
    
    
}

-(UIView *)backViewWithFloat:(CGFloat)y andField:(UITextField *)textField andImage:(UIImage *)image
{
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, y, screenWidth, cellHeight)];
    
    CGSize size = CGSizeMake(image.size.width, image.size.height);
    UIImageView *imaV = [[UIImageView alloc]initWithImage:image];
    imaV.frame = CGRectMake(29 * kWidth, (cellHeight - size.height)/2.0, size.width, size.height);
    [view addSubview:imaV];
    
    textField.frame = CGRectMake(CGRectGetMaxX(imaV.frame) + 17, 0, screenWidth - 100, cellHeight);
    textField.font = Font(15);
    [view addSubview:textField];
    textField.delegate = self;
    textField.returnKeyType = UIReturnKeyDone;

    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, cellHeight - 0.5, screenWidth - 40, 0.5)];
    [view addSubview:label];
    label.backgroundColor = LineGrayColor;
    
    return  view;
}

//点击return 按钮 去掉
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == self.captchaTextField) {
        
        [UIView animateWithDuration:0.3 animations:^{
            /* 计算偏移量 */
            
            CGFloat height = 216;
            UIButton *button = (UIButton *)[self.view viewWithTag:400];
            CGFloat offsetHeight = CGRectGetMaxY(button.frame) - (Main_height - height- 64);
            
            
            if (offsetHeight > 0) {
                self.scrollView.contentInset = UIEdgeInsetsMake(-offsetHeight , 0, 0, 0);
                
            }
            
        } completion:^(BOOL finished) {
            
        }];
        
    }
    
    
}

-(void)dismissSelf
{
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    
    
    if ([self.backToFirst isEqualToString:@"1"]) {
        
        [self dismissViewControllerAnimated:YES completion:^{
            
            UIButton *btn = (UIButton *)[rootVC.view viewWithTag:1001];
            [rootVC pressButton:btn];
        }];
        
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.2 animations:^{
        self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        
    }];
}

-(void)sendUUID{
    //    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    CFUUIDRef uuid = CFUUIDCreate(NULL);
    assert(uuid != NULL);
    CFStringRef uuidStr = CFUUIDCreateString(NULL, uuid);
    if (![SSKeychain passwordForService:@"com.sandwish.eduOnline" account:@"user"]) {//查看本地是否存储指定 serviceName 和 account 的密码
        
        [SSKeychain setPassword: [NSString stringWithFormat:@"%@", uuidStr]
                     forService:@"com.sandwish.eduOnline"account:@"user"];
        //从钥匙串读取UUID：
        NSString *retrieveuuid = [SSKeychain passwordForService:@"com.sandwish.eduOnline"account:@"user" ];
        //       NSLog(@"SSKeychain存储显示 :第一次安装过:%@", retrieveuuid);
        
        
        self.uuidString = [NSString stringWithFormat:@"%@",retrieveuuid];
        
    }else{
        
        //曾经安装过 则直接能打印出密码信息(即使删除了程序 再次安装也会打印密码信息) 区别于 NSUSerDefault
        
        
        //从钥匙串读取UUID：
        NSString *retrieveuuid = [SSKeychain passwordForService:@"com.sandwish.eduOnline"account:@"user"];
        NSLog(@"SSKeychain存储显示 :已安装过:%@", retrieveuuid);
        
        self.uuidString = [NSString stringWithFormat:@"%@",retrieveuuid];
        

    }
}


-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
